// Copyright(c) 2011 Matthew McMullan, Jorel Lalicki and Mike Heise, Jorel Lalicki and Mike Heise. See copying.txt for details.

#ifndef __agml_pages_h__
#define __agml_pages_h__

// make sure that this file is never included directly
#ifndef __agml_agml_h__
#error "Include AGML from agml.h only. This file is not a valid entry point for the library."
#endif

#ifndef __agml_os_win

#include <unistd.h>
#include <sys/mman.h>

namespace agml {
	namespace _memory {
		class _page_allocator {
		protected:
			u64 _page_size;
		public:
			_page_allocator() {
				_page_size = sysconf(_SC_PAGESIZE);
			}
			u64 getPageSize() {
				return _page_size;
			}
			void *alloc(u32_fast num = 1) {
				return mmap(0, _page_size*num, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
			}
			void free(void *page, u32_fast num = 1) {
				munmap(page,_page_size*num);
			}
		};
	}
	_memory::_page_allocator page_allocator;
}

#else

#include <windows.h>

namespace agml {
	namespace _memory {
		class _page_allocator {
		protected:
			u32 _page_size;
		public:
			_page_allocator() {
				SYSTEM_INFO tmp;
				GetSystemInfo(&tmp);
				_page_size = tmp.dwPageSize;
			}
			u32 getPageSize() {
				return _page_size;
			}
			void *alloc(u32_fast num = 1) {
				return VirtualAlloc(0, _page_size*num, MEM_COMMIT, PAGE_READWRITE);
			}
			void free(void *page, u32_fast num = 1) {
				VirtualFree(page,_page_size*num,MEM_RELEASE);
			}
		};
	}
	_memory::_page_allocator page_allocator;
}

#endif

#endif
